package cn.dansj.gateway.utils;

import com.alibaba.fastjson2.JSON;
import org.springframework.core.NamedThreadLocal;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;

public abstract class RequestUtils {
    private static final ThreadLocal<ServerWebExchange> serverWebExchangeHolder = new NamedThreadLocal<>("Request ServerWebExchange");

    public static ServerWebExchange getServerWebExchange() {
        return serverWebExchangeHolder.get();
    }

    public static void setServerWebExchange(ServerWebExchange serverWebExchange) {
        serverWebExchangeHolder.set(serverWebExchange);
    }

    public static void removeServerWebExchange() {
        serverWebExchangeHolder.remove();
    }

    public static Mono<Void> response(String message, HttpStatus httpStatus) {
        ServerHttpResponse response = getServerWebExchange().getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setStatusCode(httpStatus);

        byte[] bytes = JSON.toJSONString(new LinkedHashMap<String, Object>() {{
            put("status", httpStatus.is2xxSuccessful());
            put("message", message);
            put("responseCode", httpStatus.value());
        }}).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        return response.writeWith(Mono.just(buffer));
    }

    public static Mono<Void> response(String message, int statusCode) {
        return response(message, HttpStatus.valueOf(statusCode));
    }
}
